package cn.exrick.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.exrick.pojo.TbPreferential;
import cn.exrick.pojo.TbPreferentialItem;
import cn.exrick.pojo.dto.ItemDto;
import cn.exrick.service.ItemService;
import cn.exrick.service.PreferentialItemService;
import cn.exrick.service.PreferentialService;
import cn.exrick.utils.ControllerUtils;
import cn.exrick.utils.WebParamUtils;
import cn.exrick.utils.mybatis.Page;
import cn.exrick.utils.mybatis.PageParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(description = "优惠方案管理")
public class PreferentialController {
    @Autowired
    PreferentialService preferentialService;
    @Autowired
    PreferentialItemService preferentialItemService;
    @Autowired
    ItemService itemService;

    @RequestMapping(value = "/sys/preferential/page", method = RequestMethod.GET)
    @ApiOperation(value = "获取优惠方案分页")
    public Page<TbPreferential> getPage(Integer pageNo, Integer pageSize) throws Exception {
        if (pageNo == null || pageNo < 0) {
            pageNo = 0;
        }
        if (pageSize == null || pageSize < 0) {
            pageSize = 10;
        }
        PageParam pageParam = new PageParam(pageNo, pageSize);
        Map<String, Object> params = new HashMap<>();
        Page<TbPreferential> page = preferentialService.findPageByCriteria(params, pageParam);
        return page;
    }

    @RequestMapping(value = "/sys/preferential/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取优惠方案")
    public List<TbPreferential> getList() throws Exception {
        Map<String, Object> params = new HashMap<>();
        List<TbPreferential> list = preferentialService.findListByCriteria(params);
        return list;
    }

    @RequestMapping(value = "/sys/preferential/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "获取优惠方案")
    public TbPreferential getPojo(@PathVariable Long id) throws Exception {
        if (id == null) {
            throw new Exception("参数不足");
        }
        return preferentialService.findById(id);
    }

    @RequestMapping(value = "/sys/preferential/save", method = RequestMethod.POST)
    @ApiOperation(value = "新增优惠方案")
    public Map<String, Object> save() throws Exception {
        Double money = WebParamUtils.getDoubleParameter(ControllerUtils.getRequest(), "money", -1);
        Double total = WebParamUtils.getDoubleParameter(ControllerUtils.getRequest(), "total", -1);
        Integer num = WebParamUtils.getIntParameter(ControllerUtils.getRequest(), "num", -1);
        Double price = WebParamUtils.getDoubleParameter(ControllerUtils.getRequest(), "price", -1);

        if (money < 0 && num < 0) {
            throw new Exception("必须设置一种优惠方式");
        }
        TbPreferential pojo = new TbPreferential();
        pojo.setMoney(new BigDecimal(money));
        pojo.setNum(num);
        pojo.setTotal(new BigDecimal(total));
        pojo.setPrice(new BigDecimal(price));
        preferentialService.save(pojo);
        return new HashMap<String, Object>() {{
            this.put("success", 1);
        }};
    }

    @RequestMapping(value = "/sys/preferential/update/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "更新优惠方案")
    public Map<String, Object> update(@PathVariable Long id) throws Exception {
        Double money = WebParamUtils.getDoubleParameter(ControllerUtils.getRequest(), "money", -1);
        Double total = WebParamUtils.getDoubleParameter(ControllerUtils.getRequest(), "total", -1);
        Integer num = WebParamUtils.getIntParameter(ControllerUtils.getRequest(), "num", -1);
        Double price = WebParamUtils.getDoubleParameter(ControllerUtils.getRequest(), "price", -1);
        if (id == null) {
            throw new Exception("请输入id");
        }
        TbPreferential pojo = preferentialService.findById(id);
        if (money < 0 && num < 0) {
            throw new Exception("必须设置一种优惠方式");
        }
        pojo.setMoney(new BigDecimal(money));
        pojo.setNum(num);
        pojo.setTotal(new BigDecimal(total));
        pojo.setPrice(new BigDecimal(price));
        preferentialService.update(pojo);
        return new HashMap<String, Object>() {{
            this.put("success", 1);
        }};
    }

    @RequestMapping(value = "/sys/preferential/add/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "更新优惠方案(增加一个商品)")
    public Map<String, Object> add(@PathVariable Long id, Long itemId) throws Exception {
        if (id == null || itemId == null) {
            throw new Exception("请输入id");
        }
        TbPreferential pojo = preferentialService.findById(id);
        if (pojo == null) {
            throw new Exception("优惠方案不存在");
        }
        ItemDto item = itemService.getItemById(itemId);
        if (item == null) {
            throw new Exception("商品不存在");
        }
        if (preferentialItemService.exist(id, itemId)) {
            throw new Exception("商品已经添加");
        }
        TbPreferentialItem preferentialItem = new TbPreferentialItem();
        preferentialItem.setPreferentialId(id);
        preferentialItem.setItemId(itemId);
        preferentialItem.setStatus(TbPreferentialItem.STATUS_ABLE);
        preferentialItemService.save(preferentialItem);
        return new HashMap<String, Object>() {{
            this.put("success", 1);
        }};
    }

    @RequestMapping(value = "/sys/preferential/remove/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "更新优惠方案(去除一个商品)")
    public Map<String, Object> remove(@PathVariable Long id, Long itemId) throws Exception {
        if (id == null || itemId == null) {
            throw new Exception("请输入id");
        }
        TbPreferential pojo = preferentialService.findById(id);
        if (pojo == null) {
            throw new Exception("优惠方案不存在");
        }
        ItemDto item = itemService.getItemById(itemId);
        if (item == null) {
            throw new Exception("商品不存在");
        }
        TbPreferentialItem preferentialItem = preferentialItemService.findByPreferentialIdAndItemId(id, itemId, null);
        if (preferentialItem == null) {
            throw new Exception("商品没有该优惠方案");
        }
        preferentialItemService.delete(preferentialItem);
        return new HashMap<String, Object>() {{
            this.put("success", 1);
        }};
    }

    //=======================================================================

    @RequestMapping(value = "/sys/preferential-item/page", method = RequestMethod.GET)
    @ApiOperation(value = "获取优惠方案关联分页")
    public Page<TbPreferentialItem> getPage(Long preferentialId, Long itemId, Integer pageNo, Integer pageSize) throws Exception {
        if (pageNo == null || pageNo < 0) {
            pageNo = 0;
        }
        if (pageSize == null || pageSize < 0) {
            pageSize = 10;
        }
        PageParam pageParam = new PageParam(pageNo, pageSize);
        Map<String, Object> params = new HashMap<>();
        if (preferentialId != null) {
            params.put("preferentialId", preferentialId);
        }
        if (itemId != null) {
            params.put("itemId", itemId);
        }
        TbPreferential preferential = null;
        ItemDto itemDto = null;
        Page<TbPreferentialItem> page = preferentialItemService.findPageByCriteria(params, pageParam);
        for (TbPreferentialItem preferentialItem : page.getResult()) {
            if (preferentialId != null) {
                if (preferential == null) {
                    preferential = preferentialService.findById(preferentialId);
                }
                preferentialItem.setPreferentialContent(preferential == null ? "未找到优惠方案" : preferential.getContent());
            } else {
                TbPreferential p = preferentialService.findById(preferentialItem.getPreferentialId());
                preferentialItem.setPreferentialContent(p == null ? "未找到优惠方案" : p.getContent());
            }

            if (itemId != null) {
                if (itemDto == null) {
                    itemDto = itemService.getItemById(preferentialItem.getItemId());
                }
                preferentialItem.setItemTile(itemDto == null ? "未找到商品" : itemDto.getTitle());
            } else {
                ItemDto i = itemService.getItemById(preferentialItem.getItemId());
                preferentialItem.setItemTile(i == null ? "未找到商品" : i.getTitle());
            }
        }
        return page;
    }

    @RequestMapping(value = "/sys/preferential-item/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取优惠方案关联列表")
    public List<TbPreferentialItem> getPreferentialItemList(Long preferentialId, Long itemId) throws Exception {
        Map<String, Object> params = new HashMap<>();
        if (preferentialId != null) {
            params.put("preferentialId", preferentialId);
        }
        if (itemId != null) {
            params.put("itemId", itemId);
        }
        List<TbPreferentialItem> list = preferentialItemService.findListByCriteria(params);
        return list;
    }

    @RequestMapping(value = "/sys/preferential-item/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "获取优惠方案关联")
    public TbPreferentialItem getPreferentialItemPojo(@PathVariable Long id) throws Exception {
        if (id == null) {
            throw new Exception("参数不足");
        }
        return preferentialItemService.findById(id);
    }

    @RequestMapping(value = "/sys/preferential-item/save", method = RequestMethod.POST)
    @ApiOperation(value = "新增优惠方案关联")
    public Map<String, Object> savePreferentialItem(Long preferentialId, Long itemId) throws Exception {
        if (preferentialId == null || itemId == null) {
            throw new Exception("参数错误");
        }

        TbPreferential preferential = preferentialService.findById(preferentialId);

        if (preferential == null) {
            throw new Exception("优惠方案不存在");
        }

        ItemDto itemDto = itemService.getItemById(itemId);

        if (itemDto == null) {
            throw new Exception("商品不存在");
        }

        if (preferentialItemService.exist(preferentialId, itemId)) {
            throw new Exception("商品已经添加");
        }

        TbPreferentialItem pojo = new TbPreferentialItem();
        pojo.setItemId(itemId);
        pojo.setPreferentialId(preferentialId);
        pojo.setStatus(TbPreferentialItem.STATUS_ABLE);
        preferentialItemService.save(pojo);
        return new HashMap<String, Object>() {{
            this.put("success", 1);
        }};
    }

    @RequestMapping(value = "/sys/preferential-item/open/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "禁用/启用优惠方案关联")
    public Map<String, Object> openPreferentialItem(@PathVariable Long id) throws Exception {
        if (id == null) {
            throw new Exception("参数不足");
        }

        TbPreferentialItem pojo = preferentialItemService.findById(id);

        if (pojo == null) {
            throw new Exception("商品优惠方案不存在");
        }

        pojo.setStatus((pojo.getStatus() == TbPreferentialItem.STATUS_UNABLE ? TbPreferentialItem.STATUS_ABLE : TbPreferentialItem.STATUS_UNABLE));
        preferentialItemService.update(pojo);
        return new HashMap<String, Object>() {{
            this.put("success", 1);
        }};
    }
}
